<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import EditRole from './EditRole.vue'
import { getRoledata, getRolelike, delRole } from '../../api/api'
import data from "@/untils/address/states.json"
const isV3 = ref(false)
let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
import { Decrypt } from '../../untils/passjs/security'
let router = useRouter()
//权限管理数据
let permissionquery = ref(null);
let permissionadd = ref(null);
let permissionedit = ref(null);
let permissionremove = ref(null);
let permissionresetPassword = ref(null);

onMounted(() => {
    console.log(Decrypt("1PJ8RMDohGmzo1Dr9nB2Z1xn/ws1SsdTfgH+jfofkytYOZBA3hAY8bymD2jFkpGa5wO9qStjPdrdZ9arROAucyR75LkTrbGAzTKqFr8oLwHhPNm5Upsfct4sokFPuSWcMCAxv0ZM8kwfrTjqFBpz6yeRQvpbpmjlw5u/nVT8mLC2ACeriixh0GGGdTYMgl3aKIFmcC3VsDtwGbztKxU3kKGewfyd36xRvExKAPfnAL0="));

    getRole()


})

import { useRouter } from 'vue-router'

// 定义的头部输入框的数据
let topdata = ref({
    roleNameOrCode: ""

})
// 表格数据
let tableData = ref([])

// 获取管理员管理的数据
async function getRole() {
    try {
        let data = await getRoledata(page.value, pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            tableData.value = data.rows
        }
    } catch (error) {
        console.log(error);

    }
}
// 渲染状态的显示
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}
// 点击查询
//    async function addschoolbaslike(){
//       console.log(topdata.value);
//       topdata.value.time = dayjs(topdata.value.time).format("YYYY-MM-DD")
//       let {data} = await getschoolbasicslike(topdata.value)
//       console.log(data);
//       if(data.code == 200){
//          tableData.value = data.data
//       }
//    }
// 点击取消按钮
//    async function cancel(){
//       topdata.value = {
//         username:"",
//       phone:"",
//       accountNonLocked:"",
//       enabled:""
//       }
//       getschoolbas()
//    }
// 点击状态按钮 切换状态
//    let chuanflag = ref(0)

async function switchchange(userId, accountNonLocked) {
    console.log("1", userId, accountNonLocked);

}
async function switchchangeenabled(userId, enabled) {
    console.log("2", userId, enabled);

}
//    // 删除
let dianjiid = ref(0)
const dialogVisible = ref(false)
function del(val) {
    dianjiid.value = val.roleId
    dialogVisible.value = true
}
async function yesdel() {
    dialogVisible.value = false
    console.log(dianjiid.value);
    try {
        let deldata = await delRole(dianjiid.value)
        console.log(deldata);
        if (deldata.code == 200) {
            ElMessage({
                message: deldata.msg,
                type: 'success',
            })
            getRole()
        }
    } catch (error) {
        console.log(error);
    }
    //   if(deldata.data.code == 200){
    //      if(deldata.data.data.affectedRows > 0){
    //         ElMessage({
    //            message: '删除成功.',
    //            type: 'success',
    //         })
    //        getRole()
    //      }
    //   }
}

// 遮罩层
let dialogFormVisible = ref(false)
// 定义 是添加还是编辑的字符串
let changeType = ref("")
//    // 添加操作
//    function add(){
//        // 点击添加按钮
// dialogFormVisible.value = true
//       // //让changeType 标识 为add
//         changeType.value = 'add'
//         formlist.value = {
//             school:"",
//             username:"",
//             tel:"",
//             person:"",
//             time:"",
//             pwd:"",
//             flag:1
//          }
//    }

//    onMounted(()=>{
//     //   getschoolbas()
//    })
// 点击重置密码
// let passwordVisible = ref(false)

// 添加这两个变量
const currentUser = ref({})
const passwordVisible = ref(false)

// 修改重置密码函数
function openResetPasswordDialog(user) {
    console.log(user, currentUser.value);

    currentUser.value = user
    passwordVisible.value = true
}
// 1. 定义表单数据
const resetForm = ref({
    newpass: ''
})
// 确认重置密码
function reactpass() {
    passwordVisible.value = false
    // 如果验证通过 则进行一下环节
    resetFormRef.value.validate((valid) => {
        if (valid) {
            // 验证通过
            ElMessage.success('The password format is correct')
            console.log(resetForm.value.newpass);
            resetForm.value.newpass = ""
            // 这里可以执行提交操作
        } else {
            // 验证失败
            return false

        }
    })

}
const resetFormRef = ref(null)
const rulesobj = {
    newpass: [
        {
            required: true,
            message: 'Please input a password',
            trigger: 'blur'
        },
        {
            // pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,16}$/,
            pattern: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z!@#$%^&*]{8,16}$/,
            message: 'Password requires a combination of 8-16 letters, numbers, and special characters',
            trigger: 'blur'
        }
    ]
}



//  传递参数
let formlist = reactive({})
function add() {
    // tableData.value = []

    Object.assign(formlist, {
        // 用户名、昵称、密码、邮箱、手机号、性别(0,1)、区域(国家/洲(省))、地址(非必填)、用户等级(1-5)
        roleName: "",
        roleCode: "",
        menus: [],
        type: "新增",
    })
    // console.log(formlist);
    // //  //点击添加按钮
    dialogFormVisible.value = true
    console.log("新增操作");
    changeType.value = 'add'

}
// function getAllMenuIds(menus) {
//     let result = [];

//     function traverse(nodes) {
//         nodes.forEach(node => {
//             result.push(node.menuId);  // 添加当前节点的 menuId
//             if (node.children && node.children.length > 0) {
//                 // traverse(node.children); 
//                 // r // 递归处理子节点
//                 result.push(node.children.)
//             }
//         });
//     }

//     traverse(menus);
//     return result;
// }

function edit(index, row) {
    // let roleName = [];
    // roleName.push(JSON.parse(localStorage.getItem("userdetail"))?.roles[0].roleName == 'admin' ? "admin": JSON.parse(localStorage.getItem("userdetail"))?.roles[0].roleName == 'distributor' ? "distributor" : JSON.parse(localStorage.getItem("userdetail"))?.roles[0].roleName == 'enduser' ? "enduser" : "")
    // console.log(roleName, "角色名称");
    // const allMenuIds = getAllMenuIds(row.menus);
    // console.log(allMenuIds, "111");
    Object.assign(formlist, {
        roleId: row.roleId,
        roleName: row.roleName,
        roleCode: row.roleCode,
        menus: row.menus,
        type: "修改",
    })
    // console.log(formlist);
    console.log(index, row);
    //  //点击编辑按钮
    //  //把row数据赋值给formlist
    // formlist = row

    //  //让changeType 标识 为update
    changeType.value = "update"
    //  //让dialogFormVisible显示
    dialogFormVisible.value = true
}
//     // 子传父的事件，关闭遮罩层
async function closechange() {
    dialogFormVisible.value = false
    // getAdmin()
    // getRole()
    try {
        let data = await getRoledata(page.value, pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            tableData.value = data.rows
        }
    } catch (error) {
        console.log(error);

    }

}
let isSearching = ref(false)
async function adminlike() {
    isSearching.value = true;
    console.log(topdata.value.roleNameOrCode);
    try {
        let res = await getRolelike(topdata.value.roleNameOrCode, page.value, pageSize.value)
        console.log(res, "like查询");
        if (res.code == 200) {
            tableData.value = res.rows
            if (res.rows.length == 0) {
                return;
            }
            total.value = res.total
        }
    } catch (error) {
        console.log(error);

    }
}
function cancel() {
    console.log("重置操作");
    isSearching.value = false;
    topdata.value = {
        roleNameOrCode: ""
    }
    page.value = 1
    getRole()
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e
    if (isSearching.value) {
        try{
            await adminlike()
        }catch(error){
            console.log(error);
        }
    } else {
        // 否则调用普通分页API
        getRole()
    }
}
const dialogTableVisible = ref(false)
const gridData = ref([
    {
        date: '2016-05-02',
        name: 'John Smith',
        address: 'No.1518,  Jinshajiang Road, Putuo District',
    },
    {
        date: '2016-05-04',
        name: 'John Smith',
        address: 'No.1518,  Jinshajiang Road, Putuo District',
    },
    {
        date: '2016-05-01',
        name: 'John Smith',
        address: 'No.1518,  Jinshajiang Road, Putuo District',
    },
    {
        date: '2016-05-03',
        name: 'John Smith',
        address: 'No.1518,  Jinshajiang Road, Putuo District',
    },
])
let dialogKey = ref(0)
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] === '*:*:*') {
        return true; // 如果有 *:*:* 权限，直接返回 true
    }
    return permissions.includes(permission);
};
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>Roles</span>
            </div>
            <div class="cont">
                <div class="one">
                    <!-- 输入角色名称或角色编码 -->
                    <div class="select">
                        <el-input v-model="topdata.roleNameOrCode" class="inp" style="width: 350px"
                            placeholder="Please enter the role name or role code">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>


                    <el-button type="primary" @click="adminlike"> query</el-button>
                    <el-button type="primary" @click="cancel">reset</el-button>
                </div>
                <div class="exp">
                    <div class="export-excel">
                        <el-button style="width: 100px" type="primary" @click="add()"
                            v-if="hasPermission('system:role:add')">
                            <el-icon>
                                <FolderAdd />
                            </el-icon>add
                        </el-button>
                    </div>
                </div>
                <div class="tab">
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true"
                        v-if="hasPermission('system:role:query')">
                        <el-table-column width="55">
                            <!-- :empty-text="!permissionquery ? '暂无权限查看' : 'NotData'" -->
                            <!-- <template #default="scope" @click="check">

                     </template> -->
                        </el-table-column>
                        <el-table-column property="roleName" label="name" />
                        <el-table-column property="roleCode" label="code" />
                        <el-table-column property="roleType" label="type">
                            <template #default="scope">
                                <span>{{ scope.row.roleType == 0 ? 'Default Role' : 'Configure roles' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="roleLevel" label="level">
                            <template #default="scope">
                                <span>{{ {
                                    undefined: 'none', 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5:
                                        'five', 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: 'ten'
                                }[scope.row.roleLevel] + 'level' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="name" label="operate" width="300">
                            <!-- v-if="scope.row.roleType !== 0" -->
                            <template #default="scope">
                                <span class="more-button" @click="edit(scope.$index, scope.row)"
                                    style="cursor: pointer;" v-if="hasPermission('system:role:edit')">
                                    edit
                                </span>
                                <span class="more-button" @click="del(scope.row)" style="cursor: pointer;"
                                    v-if="hasPermission('system:role:remove')">
                                    delete
                                </span>
                                <!-- <el-button type="primary" plain @click="edit(scope.$index, scope.row)">修改</el-button> -->
                                <!-- <el-button type="danger" plain @click=del(scope.row)>删除</el-button> -->
                                <!-- 添加“更多”按钮及下拉菜单 -->
                                <el-dropdown style="cursor: pointer;" v-if="hasPermission('system:role:authorize')">
                                    <span class="more-button">
                                        more
                                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <!-- <el-dropdown-item command="resetPassword"
                                                @click="resetPassword">重置密码</el-dropdown-item> -->
                                            <el-dropdown-item command="resetPassword" plain
                                                @click="() => router.push(`/allocation/indexallocation/admin?roleId=${scope.row.roleId}`)">
                                                <!-- 这里传递当前行数据 -->
                                                <!-- {{  permissionresetPassword ? '重置密码' : '无' }}   -->
                                                Assign administrator users
                                            </el-dropdown-item>
                                            <el-dropdown-item command="resetPassword" plain
                                                @click="() => router.push(`/allocation/indexallocation/distributor?roleId=${scope.row.roleId}`)">
                                                <!-- 这里传递当前行数据 -->
                                                <!-- {{  permissionresetPassword ? '重置密码' : '无' }}   -->
                                                Assigning distributor Users
                                            </el-dropdown-item>
                                            <el-dropdown-item command="resetPassword" plain
                                                @click="() => router.push(`/allocation/indexallocation/enduer?roleId=${scope.row.roleId}`)">
                                                <!-- 这里传递当前行数据 -->
                                                <!-- {{  permissionresetPassword ? '重置密码' : '无' }}   -->
                                                Assigning EndUers
                                            </el-dropdown-item>
                                            <!-- <el-dropdown-item command="viewDetails">查看详情</el-dropdown-item> -->
                                            <!-- 可以根据需要添加更多操作 -->
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                                <!-- <el-dialog :model-value="dialogTableVisible" style="padding: 20px;width: 580px;"
                                    @close="dialogTableVisible = false" modal-class="custom-modal">
                                    <el-table :data="gridData">
                                        <el-table-column property="date" label="Date" width="150" />
                                        <el-table-column property="name" label="Name" width="200" />
                                        <el-table-column property="address" label="Address" />
                                    </el-table>
                                </el-dialog> -->
                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
                            style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                    </div>
                    <el-dialog v-model="dialogVisible" title="detele" width="500">
                        <span>Are you sure you want to delete it</span>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">cancel</el-button>
                                <el-button type="primary" @click="yesdel()">
                                    sure
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>
                <EditRole :dialogFormVisible="dialogFormVisible" :changeType="changeType" v-model:formlist="formlist"
                    @close="closechange" :key="dialogKey"></EditRole>
                <!-- :formlist="formlist" :changeType="changeType" -->
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
            .one {
                margin: 10px;
                display: flex;
                padding: 10px;

                div {
                    margin-right: 20px;
                }
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }
            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    .my-custom-backdrop {
        background-color: rgba(255, 255, 255, .8) !important;
        /* 半透明黑色 */
    }

    ::v-deep .el-overlay {
        background-color: rgba(0, 0, 0, 0.1) !important;
        /* 更深的黑色 */
    }
}
</style>